<template>
  <div class="bookmarks-page">
    <div class="page-header">
      <h2>我的书签</h2>
      <div class="header-actions">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索书签..."
          class="search-input"
          clearable
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
    </div>

    <div class="bookmarks-grid" v-if="filteredBookmarks.length > 0">
      <el-card 
        v-for="bookmark in filteredBookmarks" 
        :key="bookmark.id"
        class="bookmark-card"
        shadow="hover"
      >
        <div class="bookmark-header">
          <h3 class="bookmark-title">{{ bookmark.title }}</h3>
          <el-tag :type="getModeColor(bookmark.mode)" size="small">
            {{ getModeName(bookmark.mode) }}
          </el-tag>
        </div>
        
        <div class="bookmark-content">
          <p class="bookmark-excerpt">{{ getExcerpt(bookmark.content) }}</p>
          <div class="bookmark-meta">
            <span class="bookmark-date">保存时间：{{ formatDate(bookmark.createdAt) }}</span>
            <span class="bookmark-length">字数：{{ bookmark.content.length }}</span>
          </div>
        </div>
        
        <div class="bookmark-actions">
          <el-button size="small" @click="continueFromBookmark(bookmark)" type="primary">
            <el-icon><Edit /></el-icon>
            继续编辑
          </el-button>
          <el-button size="small" @click="viewBookmark(bookmark)">
            <el-icon><View /></el-icon>
            查看
          </el-button>
          <el-button size="small" @click="copyBookmark(bookmark)">
            <el-icon><CopyDocument /></el-icon>
            复制
          </el-button>
          <el-button size="small" @click="shareBookmark(bookmark)">
            <el-icon><Share /></el-icon>
            分享
          </el-button>
          <el-button size="small" @click="deleteBookmark(bookmark.id)" type="danger">
            <el-icon><Delete /></el-icon>
            删除
          </el-button>
        </div>
      </el-card>
    </div>

    <div v-else class="empty-state">
      <el-empty :description="searchKeyword ? '没有找到匹配的书签' : '还没有保存任何书签'">
        <el-button type="primary" @click="$router.push('/writing')" v-if="!searchKeyword">
          开始写作并保存书签
        </el-button>
      </el-empty>
    </div>

    <!-- 查看书签对话框 -->
    <el-dialog v-model="showViewDialog" :title="selectedBookmark?.title" width="800px">
      <div class="bookmark-detail" v-if="selectedBookmark">
        <div class="detail-meta">
          <el-tag :type="getModeColor(selectedBookmark.mode)" size="small">
            {{ getModeName(selectedBookmark.mode) }}
          </el-tag>
          <span class="detail-date">{{ formatDate(selectedBookmark.createdAt) }}</span>
          <span class="detail-length">字数：{{ selectedBookmark.content.length }}</span>
        </div>
        <div class="detail-content">
          {{ selectedBookmark.content }}
        </div>
        <div class="detail-actions">
          <el-button @click="continueFromBookmark(selectedBookmark)" type="primary">
            继续编辑
          </el-button>
          <el-button @click="copyBookmark(selectedBookmark)">
            复制内容
          </el-button>
          <el-button @click="shareBookmark(selectedBookmark)">
            分享到社区
          </el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 分享确认对话框 -->
    <el-dialog v-model="showShareDialog" title="分享到社区" width="500px">
      <div class="share-preview" v-if="shareBookmark">
        <h4>{{ shareBookmark.title }}</h4>
        <p class="share-content">{{ getExcerpt(shareBookmark.content, 200) }}</p>
        <p class="share-tip">确定要将这个书签分享到社区吗？</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showShareDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmShare">确认分享</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useWritingStore } from '@/stores/writing'
import { useCommunityStore } from '@/stores/community'
import { useAuthStore } from '@/stores/auth'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()
const writingStore = useWritingStore()
const communityStore = useCommunityStore()
const authStore = useAuthStore()

const searchKeyword = ref('')
const showViewDialog = ref(false)
const showShareDialog = ref(false)
const selectedBookmark = ref(null)
const shareBookmarkRef = ref(null)

const filteredBookmarks = computed(() => {
  if (!searchKeyword.value) {
    return writingStore.bookmarks
  }
  return writingStore.bookmarks.filter(bookmark =>
    bookmark.title.includes(searchKeyword.value) ||
    bookmark.content.includes(searchKeyword.value)
  )
})

const getModeName = (mode) => {
  const names = {
    biography: '传记',
    diary: '日记',
    memoir: '回忆录'
  }
  return names[mode] || mode
}

const getModeColor = (mode) => {
  const colors = {
    biography: 'primary',
    diary: 'success',
    memoir: 'warning'
  }
  return colors[mode] || ''
}

const getExcerpt = (content, length = 200) => {
  return content.length > length ? content.substring(0, length) + '...' : content
}

const formatDate = (dateString) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

const continueFromBookmark = (bookmark) => {
  writingStore.setMode(bookmark.mode)
  writingStore.updateContent(bookmark.content)
  router.push('/writing')
  ElMessage.success('书签内容已加载到写作页面')
}

const viewBookmark = (bookmark) => {
  selectedBookmark.value = bookmark
  showViewDialog.value = true
}

const copyBookmark = async (bookmark) => {
  try {
    await navigator.clipboard.writeText(bookmark.content)
    ElMessage.success('内容已复制到剪贴板')
  } catch (err) {
    // 降级方案
    const textArea = document.createElement('textarea')
    textArea.value = bookmark.content
    document.body.appendChild(textArea)
    textArea.select()
    document.execCommand('copy')
    document.body.removeChild(textArea)
    ElMessage.success('内容已复制到剪贴板')
  }
}

const shareBookmark = (bookmark) => {
  shareBookmarkRef.value = bookmark
  showShareDialog.value = true
}

const confirmShare = () => {
  if (shareBookmarkRef.value) {
    // 将书签转换为社区帖子格式
    communityStore.addPost({
      title: shareBookmarkRef.value.title,
      content: shareBookmarkRef.value.content,
      type: shareBookmarkRef.value.mode,
      tags: ['书签分享'],
      author: {
        name: authStore.user.name,
        avatar: authStore.user.avatar
      }
    })
    
    showShareDialog.value = false
    shareBookmarkRef.value = null
    ElMessage.success('书签已分享到社区')
    
    // 询问是否前往社区查看
    ElMessageBox.confirm('是否前往社区查看分享的内容？', '分享成功', {
      confirmButtonText: '前往社区',
      cancelButtonText: '稍后查看',
      type: 'success'
    }).then(() => {
      router.push('/community')
    }).catch(() => {
      // 用户选择稍后查看
    })
  }
}

const deleteBookmark = async (bookmarkId) => {
  try {
    await ElMessageBox.confirm('确定要删除这个书签吗？', '确认删除', {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const index = writingStore.bookmarks.findIndex(b => b.id === bookmarkId)
    if (index > -1) {
      writingStore.bookmarks.splice(index, 1)
      ElMessage.success('书签删除成功')
    }
  } catch {
    // 用户取消删除
  }
}
</script>

<style scoped>
.bookmarks-page {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 15px;
  align-items: center;
}

.search-input {
  width: 300px;
}

.bookmarks-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 20px;
}

.bookmark-card {
  height: fit-content;
}

.bookmark-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.bookmark-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
  flex: 1;
  margin-right: 10px;
}

.bookmark-content {
  margin-bottom: 15px;
}

.bookmark-excerpt {
  color: #666;
  line-height: 1.6;
  margin: 0 0 12px 0;
}

.bookmark-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #999;
}

.bookmark-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  padding-top: 15px;
  border-top: 1px solid #f0f0f0;
}

.empty-state {
  text-align: center;
  padding: 80px 20px;
}

.bookmark-detail, .share-preview {
  max-height: 600px;
  overflow-y: auto;
}

.detail-meta {
  display: flex;
  gap: 15px;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
  font-size: 14px;
}

.detail-content {
  margin-bottom: 20px;
  line-height: 1.8;
  color: #333;
  white-space: pre-wrap;
}

.detail-actions {
  display: flex;
  gap: 15px;
  padding-top: 15px;
  border-top: 1px solid #f0f0f0;
}

.share-preview h4 {
  margin: 0 0 15px 0;
  color: #333;
}

.share-content {
  color: #666;
  line-height: 1.6;
  margin: 0 0 15px 0;
}

.share-tip {
  color: #999;
  font-size: 14px;
  margin: 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
